package org.kjtc.controller;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.kjtc.entity.ChargingRecord;
import org.kjtc.entity.Page;
import org.kjtc.service.ActionHistoryService;
import org.kjtc.service.ChargingRecordService;
import org.kjtc.util.Const;
import org.kjtc.util.ExcelUtil;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AbnormalChargingRecord extends BaseController{

	@Resource(name = "chargingRecordService")
	private ChargingRecordService chargingRecordService;

	@Resource(name = "actionHistoryService")
	private ActionHistoryService actionHistoryService;

	@RequestMapping (value = "/searchChargingRecordHandle")
	@ResponseBody
	public Map<String, Object> searchChargingRecordHandle(ChargingRecord chargingRecord, String page, String rows)  {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常处理查询开始");

		// 分页查询
		Page pageQuery = getPage();
		pageQuery.setCurrentPage(Integer.parseInt(page));
		pageQuery.setCurrentResult((Integer.parseInt(page) - 1) * (Integer.parseInt(rows)));
		pageQuery.setShowCount(Integer.parseInt(rows));

		// 调用service方法,取得充电集合
		List<ChargingRecord> chargingRecordHandleList = null;
		String carNumberFilePath = null;
		String datePath = null;
		File carNumberFolder = null;
		String chargingStationID = null;
		String carNumber = null;
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		try {
			chargingRecordHandleList = chargingRecordService.getChargingRecordHandlePage(chargingRecord, pageQuery);
			this.getSession().setAttribute("searchChargingRecordHandle", chargingRecord);
			if (chargingRecordHandleList != null && chargingRecordHandleList.size() > 0) {
				for(ChargingRecord pageChargingRecord : chargingRecordHandleList) {
					pageChargingRecord.setChargingProcessFile("");
					chargingStationID = pageChargingRecord.getChargingStationID();
					if (chargingStationID != null && !chargingStationID.isEmpty()) {
						carNumber = pageChargingRecord.getCarNumber();
						if (carNumber != null && !carNumber.isEmpty()) {
							carNumberFilePath = Const.CHARGINGPROCESS_PATH + chargingStationID + File.separator + carNumber + File.separator;
							if (new File(carNumberFilePath).exists()) {
								Date startChargingDTTM = pageChargingRecord.getStartChargingDTTM();
								if (startChargingDTTM != null) {
									String startChargingDate = df.format(startChargingDTTM);
									Calendar calendar = Calendar.getInstance();
									calendar.setTime(startChargingDTTM);
									datePath = startChargingDate.substring(0, 4) + File.separator +
											startChargingDate.substring(4, 6) + File.separator + startChargingDate.substring(6, 8) + File.separator;
									carNumberFolder = new File(carNumberFilePath + datePath);
									if (carNumberFolder.exists()) {
										String chargingProcessFileName = null;
										String constChargingProcessFileName = carNumber + startChargingDate + Const.ZIP_SUFFIX;
										File[] chargingProcessFiles = carNumberFolder.listFiles();
										for (File chargingProcessFile : chargingProcessFiles) {
											chargingProcessFileName = chargingProcessFile.getName();
											if (chargingProcessFileName.equals(pageChargingRecord.getCarFile()) || chargingProcessFileName.equals(constChargingProcessFileName)) {
												pageChargingRecord.setChargingProcessFile(chargingProcessFileName);
												pageChargingRecord.setChargingProcessFileCreateDate(chargingProcessFile.lastModified());
												pageChargingRecord.setChargingProcessFileSize(chargingProcessFile.length());
											}
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常处理查询异常" + e.getMessage());
			return map;
		}
		map.put("chargingRecordHandleList", chargingRecordHandleList);
		map.put("totalCnt", pageQuery.getTotalResult());
		map.put("totalPage", pageQuery.getTotalPage());
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常处理查询结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "异常处理查询");
		chargingRecord = null;
		return map;
	}

	@RequestMapping (value = "/searchAbnormalRecord")
	@ResponseBody
	public Map<String, Object> searchAbnormalRecord(ChargingRecord chargingRecord, String page, String rows)  {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常记录查询开始");

		// 分页查询
		Page pageQuery = getPage();
		pageQuery.setCurrentPage(Integer.parseInt(page));
		pageQuery.setCurrentResult((Integer.parseInt(page) - 1) * (Integer.parseInt(rows)));
		pageQuery.setShowCount(Integer.parseInt(rows));

		// 调用service方法,取得充电集合
		List<ChargingRecord> abnormalRecordList = null;
		try {
			chargingRecord.setBranchCompanyID(this.getBranchCompanyID());
			abnormalRecordList = chargingRecordService.getAbnormalRecordPage(chargingRecord, pageQuery);
			this.getSession().setAttribute("searchAbnormalRecord", chargingRecord);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常记录查询异常" + e.getMessage());
			return map;
		}
		map.put("abnormalRecordList", abnormalRecordList);
		map.put("totalCnt", pageQuery.getTotalResult());
		map.put("totalPage", pageQuery.getTotalPage());
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常电记录查询结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "异常记录查询");
		chargingRecord = null;
		return map;
	}

	@RequestMapping(value = "/updateChargingRecordHandle")
	@ResponseBody
	public Object updateChargingRecordHandle(ChargingRecord chargingRecord){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录修改开始");
		chargingRecord.setUpdateUser(this.getUesr().getUserID());
		chargingRecord.setStartChargingDTTM(Tools.str2DateTime(chargingRecord.getStartChargingDate()));
		chargingRecord.setEndChargingDTTM(Tools.str2DateTime(chargingRecord.getEndChargingDate()));
		int count = 0;
		try {
			count = chargingRecordService.updateChargingRecord(chargingRecord);
			if (count > 0) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录修改异常:" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录修改结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "异常充电记录修改");
		chargingRecord = null;
		return map;
	}
	/**
	 * 删除一条或多条电池信息
	 */
	@RequestMapping(value = "/deleteChargingRecordHandle")
	@ResponseBody
	public Object deleteChargingRecordHandle(String chargingRecordList){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录删除开始");
		ChargingRecord chargingRecord = new ChargingRecord();
		if (chargingRecordList != null && !chargingRecordList.isEmpty()) {
			chargingRecord.setChargingRecordList(chargingRecordList.split(","));
		}
		int count = 0;
		try {
			count = chargingRecordService.deleteChargingRecord(chargingRecord);
			if (count > 0) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录删除异常:" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "异常充电记录删除结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "异常充电记录删除");
		chargingRecord = null;
		return map;
	}

	@RequestMapping(value = "exportChargingRecordHandle")
	@ResponseBody
	public Map<String, Object> exportChargingRecordHandle(@RequestParam(value="checkFlag", required=false) String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONArray jsonArray = null;
		try {
			jsonArray = Tools.readJsonFile("/static/json/abnormalChargingRecordExportExcel.json", false);
			if (jsonArray == null) {
				map.put("result", "JsonError");
			} else {
				if (checkFlag != null && !checkFlag.isEmpty()) {
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出开始");
					try{
						ChargingRecord chargingRecord = (ChargingRecord) this.getSession().getAttribute("searchChargingRecordHandle");
						if (chargingRecord != null) {
							List<ChargingRecord> chargingRecordList = chargingRecordService.getChargingRecordHandle(chargingRecord);
							for (ChargingRecord chargingRecordInfo : chargingRecordList) {
								chargingRecordInfo.setChargingDate(Tools.date2Str(chargingRecordInfo.getStartChargingDTTM(), "yyyy-MM-dd"));
								chargingRecordInfo.setTotalChargingTime(Tools.formatTime(chargingRecordInfo.getTotalChargingDTTM()));
							}
							map.put("chargingRecordList", chargingRecordList);
							ExcelUtil.exportExcel("异常处理记录", jsonArray, map, response);
						}
					} catch (Exception e){
						logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出异常：" + e.getMessage());
					}
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出结束");
					actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电记录导出");
				} else {
					map.put("result", "Success");
				}
			}
		} catch (Exception e) {
			map.put("result", "JsonError");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出的JSON模板读取异常：" + e.getMessage());
		}
		return map;
	}

	@RequestMapping(value = "exportAbnormalRecord")
	@ResponseBody
	public Map<String, Object> exportAbnormalRecord(@RequestParam(value="checkFlag", required=false) String checkFlag, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		JSONArray jsonArray = null;
		try {
			jsonArray = Tools.readJsonFile("/static/json/abnormalChargingRecordExportExcel.json", false);
			if (jsonArray == null) {
				map.put("result", "JsonError");
			} else {
				if (checkFlag != null && !checkFlag.isEmpty()) {
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出开始");
					try{
						ChargingRecord chargingRecord = (ChargingRecord) this.getSession().getAttribute("searchAbnormalRecord");
						if (chargingRecord != null) {
							List<ChargingRecord> chargingRecordList = chargingRecordService.getAbnormalRecord(chargingRecord);
							for (ChargingRecord chargingRecordInfo : chargingRecordList) {
								chargingRecordInfo.setChargingDate(Tools.date2Str(chargingRecordInfo.getStartChargingDTTM(), "yyyy-MM-dd"));
								chargingRecordInfo.setTotalChargingTime(Tools.formatTime(chargingRecordInfo.getTotalChargingDTTM()));
							}
							map.put("chargingRecordList", chargingRecordList);
							ExcelUtil.exportExcel("异常记录", jsonArray, map, response);
						}
					} catch (Exception e){
						logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出异常：" + e.getMessage());
					}
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出结束");
					actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电记录导出");
				} else {
					map.put("result", "Success");
				}
			}
		} catch (Exception e) {
			map.put("result", "JsonError");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电记录导出的JSON模板读取异常：" + e.getMessage());
		}
		return map;
	}
}
